package pdi.IO;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import pdi.core.Image;

import utils.IConstants;
import au.com.bytecode.opencsv.CSVWriter;

import com.google.common.base.Joiner;


public class CSVImgWriter extends ImgWriter {

	protected String csvFile;
	protected char delimiter = ',';
	protected CSVWriter csv;
	private static final int hardCodedFields = 4;
	protected boolean append = false;


	public CSVImgWriter(String csvFile) {
		this(csvFile, false, ',');

	}
	public CSVImgWriter(String csvFile, boolean append) {
		this(csvFile, append,',');
	}

	public CSVImgWriter(String csvFile, boolean append, char delimiter) {
		super();
		this.csvFile = csvFile;
		this.delimiter = delimiter;
		this.append = append;
	}

	@Override
	public void open() {

		try{			

			if(append){
				File file = new File(csvFile);
				if(file.exists()){
					csv = new CSVWriter(new FileWriter(csvFile,append));
				}else{
					csv = new CSVWriter(new FileWriter(csvFile));
					writeHeader();
				}
			}else{
				csv = new CSVWriter(new FileWriter(csvFile));
				//write header
				writeHeader();
			}



		} catch (IOException e) {
			e.printStackTrace();
		}	

	}
	private void writeHeader() {
		csv.writeNext(Joiner.on("#").skipNulls().join(
				IConstants.ID_ATTRIBUTE,IConstants.PATH_ATTRIBUTE, 
				IConstants.WIDTH_ATTRIBUTE,IConstants.HEIGHT_ATTRIBUTE,IConstants.FEATURE_NODE).split("#"));
	}

	@Override
	public void close() {
		try {
			csv.close();
			csv = null;
		} catch (IOException e) {			
			e.printStackTrace();
		}		
	}

	@Override
	public void writeNext(Image img) {

		if(csv == null)
			throw new IllegalArgumentException("unopen file to write");

		if(img == null)
			throw new  IllegalArgumentException("Null image can't be saved");

		String[] line = null;
		if(img.getFeatureVector() != null && img.getFeatureVector().length > 0){

			line = new String[hardCodedFields + img.getFeatureVector().length];
			line[0] = img.getName();
			line[1] = img.getPath();
			line[2] = img.getWidth() + "";
			line[3] = img.getHeight() + "";

			int idx = hardCodedFields;
			for (double val : img.getFeatureVector()) {
				line[idx] = val + "";
				idx++;
			}
		}else{
			line = new String[hardCodedFields];
			line[0] = img.getName();
			line[1] = img.getPath();
			line[2] = img.getWidth() + "";
			line[3] = img.getHeight() + "";
		}
		
		csv.writeNext(line);
	}

	@Override
	public void writeAll(List<Image> imgs) {
		open();

		if(imgs != null && imgs.size() > 0){
			for (Image img : imgs) {
				writeNext(img);
			}		
		}

		close();

	}

}
